package net.libra.ui
{
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.text.TextField;
	import flash.utils.Dictionary;
	import flash.utils.Timer;
	/**
	 * @author elvisjiang
	 */
	public class TimeTextControl
	{
		static public const TIME_UP:String = "timeUp";
		
		static protected var map:Dictionary;
		static protected var timer:Timer;
		static public function setTimeText(field:TextField,content:Object,sec:Number):void
		{
			sec = Math.ceil(sec);
			
			if(!map)
			{
				map = new Dictionary();
				timer = new Timer(1000);
				timer.addEventListener(TimerEvent.TIMER,run);
				timer.start();
			}
			
			if(sec > 0)
			{
				map[field] = {content:content,sec:sec};
			}
			
			if(content is String)
			{
				field.htmlText = content.replace("{time}",getTimeString(sec));
			}else
			{
				field.htmlText = content(sec);
			}
		}
		static protected function run(event:TimerEvent):void
		{
			var list:Array = [];
			for(var key:Object in map)
			{
				list.push({field:key,obj:map[key]});
			}
			
			for(var i:uint=0;i<list.length;i++)
			{
				var data:Object = list[i];
				var field:TextField = data.field;
				var obj:Object = data.obj;
				obj.sec --;
				if(obj.sec <= 0)
				{
					obj.sec = 0;
				}
				var content:Object = obj.content;
				var sec:Number = obj.sec;
				
				if(content is String)
				{
					field.htmlText = content.replace("{time}",getTimeString(sec));
				}else
				{
					field.htmlText = content(sec);
				}
				
				if(obj.sec <= 0)
				{
					removeTimeText(field);
					field.dispatchEvent(new Event(TimeTextControl.TIME_UP,true));
				}
			}
		}
		static protected function getTimeString(sec:Number):String
		{
			if(sec <= 0)
			{
				sec = 0;
			}
			var hour:Number = int(sec / 60 / 60);
			sec -= hour *60 * 60;
			var min:Number = int(sec / 60);
			sec -= min *60;
			sec = int(sec);
			var content:String = "";
//			if(hour > 0)
//			{
			content = String("0"+hour).substr(-2) + ":";
//			}
			content += String("0"+min).substr(-2) + ":";
			content += String("0"+sec).substr(-2);
			return content;
		}
		static public function removeTimeText(field:TextField):void
		{
			if(map && map[field])
			{
				delete map[field];
			}
		}
	}
}